(function() {
    /* FormatTreeData ---S */
    function FormatTreeData(opt) {
        this.id = opt.id || "id";
        this.pId = opt.pId || "parent_id";
        this.emitId = opt.emitId || "0";
        this.treeJson = {};
    }
    FormatTreeData.prototype = {
        getTreeData:function(data) {
            //console.log(data);
            for (var i = 0, len = data.length; i < len; i++) {
                var t = data[i];
                if (!this.treeJson[t[this.pId]]) {
                    this.treeJson[t[this.pId]] = [];
                    this.treeJson[t[this.pId]].push(t);
                } else {
                    this.treeJson[t[this.pId]].push(t);
                }
            }
            //console.log(this.treeJson);
            //
            function format(pId) {
                var result = [];
                if (!this.treeJson[pId]) {
                    return result;
                }
                for (var i in this.treeJson[pId]) {
                    var t = this.treeJson[pId][i];
                    t.children = format.call(this, t[this.id]);
                    result.push(t);
                }
                return result;
            }
            return format.call(this, this.emitId);
        },
        transferTreeData:function(treeData) {
            let result = [];
            treeData.forEach(item => {
                result.push(item);
                pushDataToResult(item.children);
            });

            function pushDataToResult(arr) {
                while (arr.length) {
                    let item = arr.shift();
                    result.push(item);
                    if (item.children) {
                        pushDataToResult(item.children);
                    }
                }
            }
            result.forEach(item => {
                delete item.children;
            })
            return result;
        },
        reset:function(opt) {
            this.id = opt.id || "id";
            this.pId = opt.pId || "parent_id";
            this.emitId = opt.emitId || "0";
            this.treeJson = null;
            this.treeJson = {};
            return this;
        }
    };
    window.zzFormatTreeData = FormatTreeData;
    /* FormatTreeData ---E */
})();